from Accounting.Entity.Base import Fund
from Accounting.Entity.Client import *
from DataAccess.DBConnFactory import DBConnFactory
from datetime import date
from string import Template	


class Feeder(Fund):
	def __init__(self, id, parent):
		Fund.__init__(self, id, parent)
				
	def retrieving_cash(self, cf, child):
		if self.parent:
			redemption_action = Redemption(cf.date(), cf.amount(), cf.currency())
			self.parent.redeming_fund(redemption_action, self)

	def create_children(self):
		ids = self.query_children_id()
		self.children_roster = {}
		
		for item in ids:
			self.children_roster[item] = Client(item, self)
			
			
	def residual_cash(self, ref_date):
		cursor = DBConnFactory().get_db_connection('ACCOUNTING').cursor()		
		sql_tpl = Template('''select sum(amount) amount,curncy
							from cash_chg
							where ref_date<=TO_DATE('${DATE}','yyyy-mm-dd')
								and entity='${ENTITY}'
							group by curncy''')
		cursor.execute(sql_tpl.substitute(DATE=ref_date.isoformat(),
										ENTITY=self.get_entity_id()))
		r = cursor.fetchone()
		#assert r and len(r)==2
		if not r: #inception date
			return 0.0
			
		return r[0]